`
https://leetcode.cn/problems/continuous-subarrays/
`

/**
 * @param {number[]} nums
 * @return {number}
 */
var continuousSubarrays = function (nums) {
  const n = nums.length
  // 使用两个单调队列维护窗口内的最大值和最小值
  const maxQ = new Deque()
  const minQ = new Deque()
  let res = 0
  let left = 0, right = 0

  while (right < n) {
    const n1 = nums[right]
    // 更新队列，维护最值
    while (!maxQ.isEmpty() && n1 >= nums[maxQ.back()]) maxQ.popBack()
    maxQ.pushBack(right)
    while (!minQ.isEmpty() && n1 <= nums[minQ.back()]) minQ.popBack()
    minQ.pushBack(right)
    right++

    // 最值差值 > 2 ，缩小窗口
    while (nums[maxQ.front()] - nums[minQ.front()] > 2) {
      // 若队列头已不在窗口里便弹出
      if (maxQ.front() <= left) maxQ.popFront()
      if (minQ.front() <= left) minQ.popFront()
      left++
    }

    res += right - left
  }

  return res
};